/**
 * Inject the embeded script into a page and set listeners to the 
 * localStorage value.
 */

(function(){
	/**
	 * Chrome listeners
	 */
	chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
		if (request.action == "testPage") {
			init();
			sendResponse({});
		}
	});
	
	function notifyBackgroundPage() {
		chrome.extension.sendRequest({setLibs: localStorage[localStorage_key]}, function(response) {
			//delete the storage key
			localStorage.removeItem(localStorage_key);
			
			//remove embeded scripts
			removeEmbededScript();
			
			//notify that test is done
			test_running = false;
		});
	}
	
	
	var scripts = ["js/embeded_scripts/libraries_test.js"],
		scripts_id_prefix = "LD_",
		embeded_scripts = [],
	    localStorage_key = "LD",
	    test_running = false;
	
	/**
	 * 
	 */
	function embedScript(){
		var i = 0,
			script,
			body = document.body,
			fragment = document.createDocumentFragment();
		
		for (i; i < scripts.length; i++) {
			script = document.createElement("script");
			script.id = scripts_id_prefix + (i+1);
			script.type = "text/javascript";
			script.src = chrome.extension.getURL(scripts[i]);
			fragment.appendChild(script);
			embeded_scripts.push(script);
		};
		
		body.appendChild(fragment);
	}
	
	/**
	 * 
	 */
	function removeEmbededScript(){
		var i = 0,
			body = document.body;
		
		for (i; i < embeded_scripts.length; i++) {
			body.removeChild(embeded_scripts[i]);
		}
	}
	
	/**
	 * 
	 */
	function handleStorageChange(storageEvent){
		if (storageEvent.key !== localStorage_key || 
				(storageEvent.key === localStorage_key && storageEvent.newValue === "")) {
			return;
		}
		
		//notify the background page that storage changed
		notifyBackgroundPage();
	}
	
	/**
	 * 
	 */
	function initializeLocalStorage(){
		localStorage[localStorage_key] = null;
		document.body.addEventListener("storage", handleStorageChange, false);
	}
	
	/**
	 * 
	 */
	function init(){
		if (test_running) {
			return;
		}
		
		test_running = true;
		initializeLocalStorage();
		embedScript();
	};
})();